package me.ohaga
{
	import flash.utils.ByteArray;
	
	import net.flashpunk.World;
	import net.flashpunk.graphics.Tilemap;

	
	
	public class LevelResource extends World
	{
		[Embed(source = "assets/maps/testmap.tmx", mimeType="application/octet-stream")] private var LEVEL_TEST:Class;
		[Embed(source = "assets/gfx/tiles.png")] private var TILES_IMG:Class;
		
		private var rawData:ByteArray = new LEVEL_TEST;
		private var activeTilemap:Tilemap;
		private var _player:Player;
		
		public function LevelResource(currentWorld:int = 0)
		{
		
			super();
		}
		
		override public function begin():void
		{
			setMap();
			
		}
		
		public function setMap():void
		{
			var dataString:String = rawData.readUTFBytes(rawData.length);
			var xmlData:XML = new XML(dataString);
			
			//trace(xmlData);
			var cols:uint = xmlData.@width;
			var rows:uint = xmlData.@height;
			var tileW:uint = xmlData.@tilewidth;
			var tileH:uint = xmlData.@tileheight;
			
			var tiles:XMLList = xmlData.layer.(@name == "mapLayer").data.tile;
			var types:XMLList = xmlData.tileset.tile;
			trace(tiles);
			
			var typeArray:Array = new Array();
			
			for each (var tile : XML in types)
			{
				trace(tile.attributes());
				trace(tile.properties.property.@value);
				typeArray[tile.attributes()] = tile.properties.property.@value;
			}
			trace(typeArray);
			activeTilemap = new Tilemap(TILES_IMG, cols, rows, tileW, tileH);
			var tx:uint = 0;
			var ty:uint = 0;
			for each (var t : XML in tiles)
			{
				//trace(t.@gid);
				var x:int = t.@gid - 1;
				if(typeArray[x] == "wall")
				{
					add(new Block(tx*tileW, ty*tileH));
				}
				else if (typeArray[x] == "start")
				{
					_player = new Player(tx*tileW, (ty-1)*tileH);
					add(_player);
				}
				else if (typeArray[x] == "exit")
				{
					trace("exit: "+tx+", "+ty);
					//exit shit
				}
				if(tx+1 < cols)
				{
					tx++;
				}
				else
				{
					ty++;
					tx=0;
				}
			}
			
			
		}
	}
}